<template>
  <div class="total-box">
    <el-row :gutter="20" class="full-row">
      <!--部门数据-->
      <div class="full-height" style="padding: 20px; overflow: auto">
        <el-input
          v-model="filterText"
          prefix-icon="el-icon-search"
          placeholder="输入关键字进行过滤"
          clearable
          @keyup.enter.native="handleFilter(filterText)"
          @clear="handleFilter(filterText)"
        />
        <div class="head-container" style="flex: 1; overflow: auto">
          <el-tree
            ref="tree"
            :expand-on-click-node="false"
            :default-expanded-keys="expandedKeys"
            :data="deptOptions"
            :props="defaultProps"
            :current-node-key="currentNodeKey"
            :filter-node-method="filterNode"
            node-key="orgId"
            highlight-current
            @node-click="handleNodeClick"
          >
            <template slot-scope="{node,data}">
              <span class="el-tree-node_box" :title="data.terminalName">{{ data.terminalName }}</span>
            </template>
          </el-tree>
        </div>
      </div>
      <div class="right">
        <div class="flex-between">
          <HkSearchform
            :data="queryParams"
            :field-list="filterInfo.fieldList"
            :list-type-info="dictList"
            @handleSearch="handleQuery"
            @handleReset="resetQuery"
            @handleEvent="handleEvent"
          />
          <el-row :gutter="10">
            <el-button icon="el-icon-download" size="small" @click="importTemplate">下载模板</el-button>
            <el-button size="small" @click="handleImport">导入</el-button>
            <el-button size="small" @click="handleExport">导出</el-button>
          </el-row>
        </div>
        <div class="flex-between">
          <el-tabs v-model="targetType" @tab-click="val=>getDataList({targetType:val.name})">
            <el-tab-pane v-for="(i,idx) in typeArr" :key="idx" :label="i.name" :name="i.value" />
          </el-tabs>
          <div>
            <el-button type="primary" icon="el-icon-plus" size="small" :disabled="!terminalObj.terminalIp" @click="handleAdd">新建</el-button>
            <el-button
              size="small"
              :disabled="!ids.length"
              icon="el-icon-circle-close"
              @click="handleDelete"
            >取消授权</el-button>
          </div>
        </div>

        <hk-table
          ref="tableRef"
          :loading="loading"
          :table-data="tableData"
          :table-columns="tableList"
          :selection="true"
          :show-index="true"
          :total="total"
          :table-height="80"
          :query-params="queryParams"
          @handleSelectionChange="handleSelectionChange"
          @changePage="getDataList"
        >
          <template #type="scope">
            <dict-label :options="dictList.typeList" :value="scope.row.type" />
          </template>
          <template #isAll="scope">
            <dict-label :options="dictList.isAllList" :value="scope.row.isAll" />
          </template>
          <template #terminalIp="scope">
            <el-popover placement="bottom-start" width="300" trigger="hover">
              <div class="popver">
                <p>设备名称：{{ scope.row.terminal.hostName ||'' }}</p>
                <p>责任人：{{ scope.row.terminal.userName||'' }}</p>
                <p>
                  人员岗位属性：
                  <dict-label :options="dictList.userBusTypeList" :value="scope.row.terminal.userBusType" />
                </p>
                <p>责任部门：{{ scope.row.terminal.orgName||'' }}</p>
                <p>
                  类型：
                  <dict-label :options="dictList.equipmentTypeList" :value="scope.row.type" />
                </p>
              </div>
              <span slot="reference">{{ scope.row.terminalIp }}</span>
            </el-popover>
          </template>
          <template #targetIp="scope">
            <el-popover placement="bottom-start" width="300" trigger="hover">
              <div class="popver">
                <p>设备名称：{{ scope.row.target.deviceName ||'' }}</p>
                <p>责任人：{{ scope.row.target.userName||'' }}</p>
                <p>
                  人员岗位属性：
                  <dict-label :options="dictList.userBusTypeList" :value="scope.row.target.userBusType" />
                </p>
                <p>责任部门：{{ scope.row.target.orgName ||'' }}</p>
                <p>
                  类型：
                  <dict-label :options="dictList.equipmentTypeList" :value="scope.row.type" />
                </p>
              </div>
              <span slot="reference">{{ scope.row.targetIp }}</span>
            </el-popover>
          </template>
          <!-- <template #operate="scope">
            <el-button size="mini" type="text" @click="handleUpdate(scope.row)">编辑</el-button>
            <el-button size="mini" type="text" @click="handleDelete(scope.row)">删除</el-button>
          </template> -->
        </hk-table>
      </div>
    </el-row>

    <!-- 右侧数据 -->
    <!-- 新增和编辑的对话框 -->
    <edit-dialog
      ref="editDialogRef"
      :title="title"
      :dict-list="dictList"
      :terminal-obj="terminalObj"
      :target-type="targetType"
      @handleSubmit="getTree('reset')"
    />
    <!-- 输出 -->
    <import-dialog ref="import_dia" @submit="getTree" />
  </div>
</template>

<script>
import HkTable from '@/components/Hk-Table/index.vue'
import EditDialog from './component/emitDialog.vue'
import HkSearchform from '@/components/HkSearchform/index.vue'
import DictLabel from '@/components/Common/dictLabel.vue'
import ImportDialog from './component/ImportDialog.vue'
import {
  getTerminalTree,
  pageList,
  deleteList,
  listByTypes,
  getOperationType
} from '@/api/approval/maintenancePermissions.js'

export default {
  components: {
    HkTable,
    EditDialog,
    HkSearchform,
    DictLabel,
    ImportDialog
  },
  data() {
    return {
    // 当前选中项
      currentNodeKey: 'root',
      // 默认展开
      expandedKeys: [],
      // 部门列表
      deptOptions: [],
      defaultProps: {
        children: 'children',
        label: 'terminalName',
        id: 'orgId',
        ip: 'terminalIp'
      },
      // 设备类型
      targetType: '',
      // 设备信息
      terminalObj: {},
      // 设备类型数组
      typeArr: [],
      treeId: '',
      filterText: '',
      // 搜索项配置
      filterInfo: {
        fieldList: [
          { label: '关键字', type: 'input', field: 'keyword' },
          {
            label: '运维方式 ',
            type: 'select',
            field: 'type',
            list: 'typeList'
          }
        ]
      },
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,

      // 表格数据
      tableData: [],
      //  表格
      tableList: [
        { label: '运维对象名称', param: 'targetName' },
        { label: '运维对象IP', param: 'targetIp', type: 'slot' },
        { label: '运维方式', param: 'type', type: 'slot' },
        // { label: '运维对象IP', param: 'targetIp', type: 'slot' },
        { label: '运维协议', param: 'protocol' },
        { label: '运维端口', param: 'port' },
        { label: '允许时间段', param: 'isAll', type: 'slot' }
      ],
      // 弹出层标题
      title: '',

      // 查询参数
      queryParams: {
        size: 10,
        current: 1,
        orgId: '',
        ip: ''
      },
      // 列表规则
      dictList: {
        typeList: [
          {
            label: '远程运维',
            value: '1'
          },
          {
            label: '本地运维',
            value: '2'
          }
        ],
        isAllList: [
          {
            label: '全部时间段',
            value: '1'
          },
          {
            label: '其他',
            value: '0'
          }
        ],
        terminalNameList: [],
        targetNameList: [],
        userBusTypeList: [
          {
            label: '普通用户',
            value: '1'
          },
          {
            label: '运维用户',
            value: '2'
          },
          {
            label: '业务用户',
            value: '3'
          }
        ],
        equipmentTypeList: []
      }
    }
  },
  mounted() {
    this.getTree()
    this.getDictList()
    getOperationType().then(res => {
      this.typeArr = res
    })
  },
  methods: {
  // 获取左侧树节点
    getTree(val) {
      getTerminalTree().then(res => {
        this.deptOptions = res
        this.expandedKeys = res.map(item => {
          const child = item.children.map(i => i.orgId)
          return [item.orgId, ...child]
        }).reduce((total, i) => {
          return total += i.join(',')
        }, '').split(',')
        this.$nextTick(function() {
          this.$refs.tree.setCurrentKey(this.currentNodeKey)
        })
      })
      if (!val) { this.targetType = '' }

      this.getDataList({ targetType: this.targetType })
    },
    //  左侧筛选
    handleFilter(val) {
      this.$refs.tree.filter(val)
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true
      return data.terminalName.includes(value)
    },
    // 节点单击事件
    handleNodeClick(data) {
      let ip = ''
      let orgId = ''
      this.currentNodeKey = data.orgId
      if (data.terminalIp) {
        const { terminalIp, terminalName, terminalUserName, orgParentId: terminalOrgId, orgId: selectKey } = data
        this.terminalObj = { terminalIp, terminalName, terminalUserName, terminalOrgId, selectKey }
        ip = data.terminalIp
        orgId = ''
      } else {
        orgId = data.orgId
        this.terminalObj = {}
      }
      this.targetType = ''
      // this.queryParams.ip = ip
      this.getDataList({ ip, orgId, targetType: '' })
    },

    /** 查询用户列表 */
    getDataList(val) {
      this.loading = true
      this.queryParams = { ...this.queryParams, ...val, scrollToTop: true }
      pageList(this.queryParams).then(res => {
        this.total = res.total
        this.tableData = res.list
        this.loading = false
        this.queryParams.scrollToTop = false
      })
    },
    getDictList() {
      listByTypes('equipmentType').then(res => {
        this.dictList.equipmentTypeList = res.equipmentType.map(item => {
          return {
            label: item.itemLabel,
            value: item.itemVale
          }
        })
      })
    },
    /** 搜索按钮操作 */
    handleQuery(val) {
      this.queryParams.current = 1
      this.targetType = ''
      this.getDataList({ targetType: this.targetType })
    },
    // 重置表单
    resetQuery() {
      // for (const key in this.queryParams) {
      //   this.queryParams[key] = undefined
      // }
      this.targetType = ''
      this.queryParams.keyword = ''
      this.queryParams.type = ''
      this.queryParams.size = 10
      this.queryParams.current = 1

      this.getDataList()
    },
    // 搜索框变化
    handleEvent(val) {
      const field = val.field
      const value = val.value
      this.queryParams = {
        ...this.queryParams,
        ...{
          [field]: value
        }
      }
    },

    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length != 1
      this.multiple = !selection.length
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.title = '添加'
      this.$refs.editDialogRef.show()
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.title = '编辑'

      this.$refs.editDialogRef.show(row.id)
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const id = row.id || this.ids.join(',')
      this.$modal
        .confirm('是否确认取消所选项授权？')
        .then(function() {
          return deleteList(id)
        })
        .then(() => {
          this.$modal.msgSuccess('取消授权成功')
          this.getDataList()
        })
        .catch(error => {
          console.log(error)
        })
    },
    /** 导入按钮操作 */
    handleImport() {
      this.$refs.import_dia.upload.open = true
    },
    /** 下载模板操作 */
    importTemplate() {
      this.gDownload(window.baseUrl.icp + '/approve/operate/template', {}, `运维权限审批模板.xlsx`)
    },
    /** 导出按钮操作 */
    handleExport() {
      this.gDownload(
        window.baseUrl.icp + '/approve/operate/export',
        {
          ...this.queryParams
        },
        `运维权限审批${new Date().getTime()}.xlsx`
      )
    }
  }
}
</script>
  <style lang="scss" scoped>
.app-container {
  display: flex;
  flex-direction: column;
}
.total-box {
  font-size: 14px;
  display: flex;
  width: 100%;
  height: 100%;
}
.head-container {
  overflow: auto;
  padding: 10px 0;
  height: 100%;
  width: 100%;
  // border-right: 1px solid rgba(0, 0, 0, 0.08);
}
.right {
  width: calc(100% - 270px);
  height: 100%;
  display: flex;
  flex-direction: column;
  padding: 20px;
}
.full-row {
  width: 100%;
  height: 100%;
  display: flex;

  .full-height {
    height: 100%;
    display: flex;

    width: 270px;
    flex-direction: column;
    border-right: 1px solid rgba(0, 0, 0, 0.08);
    .head-container {
      margin-top: 10px;
      .title {
        font-size: 14px;
        padding: 5px 10px !important;
        background: #f8f8f8;
        .tit-left {
          flex: 1;
          span {
            margin-left: 10px;
          }
        }
      }
    }
  }
  .custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
}
.flex-between {
  display: flex;
  justify-content: space-between;
  align-items: flex-end;
  & + .flex-between {
    margin-top: 20px;
  }
}
.targetTable {
  flex: 1;
  overflow: hidden;
}
.el-row {
  display: flex;
  flex-wrap: wrap;
  margin: 0 !important;
}
.popver {
  p + p {
    margin-top: 5px;
  }
  p {
    display: flex;
    align-items: center;
  }
}
.content {
  padding-bottom: 0;
}
::v-deep {
  .el-tabs__nav-wrap::after {
    display: none;
  }
  .el-tabs__header {
    margin: 0;
  }
  .el-tree{
    width: 100%;
  }
  .targetTable .el-table{
    overflow: hidden;
  }
}
</style>

